package com.youlai.system.controller;

import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.system.common.base.IBaseEnum;
import com.youlai.system.common.enums.TaskStatusEnum;
import com.youlai.system.common.enums.TaskTypeEnum;
import com.youlai.system.common.result.PageResult;
import com.youlai.system.common.result.Result;
import com.youlai.system.model.entity.SysDept;
import com.youlai.system.model.entity.SysTask;
import com.youlai.system.model.query.TaskPageQuery;
import com.youlai.system.model.vo.TaskPageVO;
import com.youlai.system.service.ImportDataExecService;
import com.youlai.system.service.SysDeptService;
import com.youlai.system.service.SysTaskService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 任务控制器
 */
@Tag(name = "16.任务接口")
@RestController
@RequestMapping("/api/v1/tasks")
@RequiredArgsConstructor
public class SysTaskController {

    private final SysTaskService taskService;

    private final ImportDataExecService importDataExecService;

    private final SysDeptService deptService;

    @Operation(summary = "任务分页列表")
    @GetMapping("/page")
    public PageResult<TaskPageVO> getTaskPage(@ParameterObject TaskPageQuery queryParams) {
        IPage<TaskPageVO> result = taskService.getTaskPage(queryParams);
        List<SysDept> deptList = deptService.list();
        Map<Long, String> deptNameMap = deptList.stream().collect(Collectors.toMap(SysDept::getId, SysDept::getName));
        result.getRecords().forEach(taskPageVO -> {
            taskPageVO.setTypeStr(IBaseEnum.getLabelByValue(taskPageVO.getType(), TaskTypeEnum.class));
            taskPageVO.setStatusStr(IBaseEnum.getLabelByValue(taskPageVO.getStatus(), TaskStatusEnum.class));
            if (taskPageVO.getStartTime() != null && taskPageVO.getEndTime() != null) {
                String timeInterval = DateUtil.formatBetween(LocalDateTimeUtil.between(taskPageVO.getStartTime(), taskPageVO.getEndTime()).toMillis(), BetweenFormatter.Level.SECOND);
                taskPageVO.setTimeInterval(timeInterval);
            }
            if (taskPageVO.getDeptId() != null) {
                taskPageVO.setDeptName(deptNameMap.get(taskPageVO.getDeptId()));
            }
        });
        return PageResult.success(result);
    }

    @Operation(summary = "一键导入数据")
    @PostMapping("/_import")
    @PreAuthorize("@ss.hasPerm('sys:task:import')")
    public Result importUsers(@Parameter(description = "部门ID") Long deptId, @Parameter(description = "类型ID") Integer typeId, MultipartFile file) throws IOException {
        SysTask task = new SysTask();
        task.setType(typeId);
        task.setDeptId(deptId);
        task.setContent(file.getOriginalFilename());
        task.setStatus(TaskStatusEnum.EXECUTING.getValue());
        task.setStartTime(LocalDateTime.now());
        taskService.save(task);
        importDataExecService.uploadImport(task.getId(), deptId, typeId, file.getInputStream());
        return Result.success("正在导入");
    }

    @Operation(summary = "删除任务")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:task:delete')")
    public Result deleteTasks(
            @Parameter(description = "任务ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = taskService.deleteTasks(ids);
        return Result.judge(result);
    }
}
